package com.dream.service.user.impl.erp;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseListResponse;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.common.model.response.ListModel;
import com.dream.service.user.api.erp.UserServiceERP;
import com.dream.service.user.dao.UserDao;
import com.dream.service.user.domain.entity.TimeSpan;
import com.dream.service.user.domain.entity.User;
import com.dream.service.user.domain.model.UserModel;
import com.dream.service.user.domain.request.UserCondition;
import com.dream.service.user.domain.request.UserSelectCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by kangd on 2016/3/24.
 */
public class UserServiceERPImpl implements UserServiceERP {
    //DAO
    private UserDao userDao;

    private Logger logger = LoggerFactory.getLogger(UserServiceERPImpl.class);

    public UserDao getUserDao() {
        return userDao;
    }

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    /**
     * 管理用户，拉黑等
     *
     * @param user@return
     */
    @Override
    public BaseResponse<Boolean> managerUserInfo(User user) {
        return null;
    }

    /**
     * 用户查询条件
     * @param userSelectCondition
     * @return
     */
    @Override
    public BaseListResponse UserList(UserSelectCondition userSelectCondition) {
        long startTime = System.currentTimeMillis();
        if(userSelectCondition == null ){
            BaseListResponse baseListResponse= new BaseListResponse(ErrorCode.PARAM_ERROR);
            return baseListResponse;
        }
        BaseListResponse baseListResponse= new BaseListResponse();
        ListModel listModel = new ListModel();
        List<UserModel> userModels;
        try {
            userModels = userDao.selectBySelective(userSelectCondition);
            listModel.setList(userModels);
            listModel.setAmount(userDao.selectCountBySelective(userSelectCondition));
            baseListResponse.packData(true, ErrorCode.OK.getCode(), "", null, listModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseListResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseListResponse.setLatency(System.currentTimeMillis()-startTime);
        return baseListResponse;
    }

    @Override
    public BaseResponse<Boolean> updateUser(UserModel model){
        long startTime = System.currentTimeMillis();
        if(model == null || StringUtils.isEmpty(model.getPin())){
            BaseResponse<Boolean> baseResponse= new BaseResponse<Boolean>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }
        BaseResponse<Boolean> baseResponse= new BaseResponse<Boolean>();
        try {
            int i=userDao.updateUserNetRed(model);
            if(i==1){
                baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, true);
            }else{
                baseResponse.packData(false, ErrorCode.PROCESS_ERROR.getCode(), "", null, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseResponse.setLatency(System.currentTimeMillis()-startTime);
        return baseResponse;
    }

    @Override
    public BaseListResponse queryByCondition(UserCondition queryCondition) {
        BaseListResponse baseListResponse = new BaseListResponse();
        try {
            if (queryCondition == null) {
                baseListResponse.packData(false, ErrorCode.PARAM_ERROR.getCode(), "", null, null);
                return baseListResponse;
            }
            Integer pageNum = queryCondition.getPageNum();
            Integer pageSize = queryCondition.getPageSize();
            if (pageNum == null || pageNum <= 0) {
                pageNum = 1;
                queryCondition.setPageNum(1);
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
                queryCondition.setPageSize(10);
            }
            queryCondition.setStart((pageNum - 1) * pageSize);
            String sort = queryCondition.getSort();
            if(StringUtils.isEmpty(sort)){
                sort = "update_time desc";
                queryCondition.setSort(sort);
            }
//        String login_email,nickname,pin,createTime,user_type,status_code
//            TimeSpan createTime = queryCondition.getCreateTime();
//            if (createTime == null) {
//                createTime = new TimeSpan();
////                createTime.setStartTime(0L);
////                createTime.setEndTime(System.currentTimeMillis() + 10000);//如果是没有填写，日期默认后延期时间
//                queryCondition.setCreateTime(createTime);
//            }
//            else {
//                String start = createTime.getStartTime();
//                if (start == null) {
//                    createTime.setStartTime(0L);
//                }
//                if (createTime.getEndTime() == null) {
//                    createTime.setEndTime(System.currentTimeMillis() + 10000);
//                }
//            }
            if (logger.isInfoEnabled()) {
                logger.info("[userserviceErp]queryByCondition,condition:{}", JSONObject.toJSONString(queryCondition));
            }

//            TimeSpan last_order_time = queryCondition.getLast_order_time();
//            if (last_order_time == null) {
//                last_order_time = new TimeSpan();
////                last_order_time.setStartTime(0L);
////                last_order_time.setEndTime(System.currentTimeMillis() + 10000);//如果是没有填写，日期默认后延期时间
//                queryCondition.setLast_order_time(last_order_time);
//            }
//            else {
//                Long start = last_order_time.getStartTime();
//                if (start == null) {
//                    last_order_time.setStartTime(0L);
//                }
//                if (last_order_time.getEndTime() == null) {
//                    last_order_time.setEndTime(System.currentTimeMillis() + 10000);
//                }
//            }
            List<UserModel> userModels = userDao.queryByCondition(queryCondition);
            //获取count
            Integer count = userDao.queryCountByCondition(queryCondition);
            ListModel listModel = new ListModel();
            baseListResponse.setResult(listModel);
            listModel.setAmount(count);
            listModel.setPageSize(pageSize);
            listModel.setCurrentPageNum(pageNum);
            listModel.setList(userModels);
            int pageAmout = 0;
            if (count > 0) {
                pageAmout = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            }
            listModel.setPageAmount(pageAmout);
            if (logger.isInfoEnabled()) {
                logger.info("[userserviceErp]queryByCondition,result:{}", JSONObject.toJSONString(baseListResponse));
            }
            baseListResponse.packData(true, ErrorCode.OK.getCode(), "", null, listModel);
        }catch (Exception e){
            logger.error("[userserivceerp]queryByCondition process error:{},request:{} ",e,JSONObject.toJSONString(queryCondition));
            baseListResponse.packData(false, ErrorCode.PROCESS_ERROR.getCode(), "query failed", null, null);
        }
        return baseListResponse;
    }
}
